package com.ruoyi.project.newhope.data.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.ruoyi.project.newhope.data.domain.EchartsVO;
import com.ruoyi.project.newhope.data.domain.NewHopeData;
import com.ruoyi.project.newhope.data.domain.NewHopeUnInit;
import com.ruoyi.project.newhope.data.mapper.NewHopeCollectDataMapper;
import com.ruoyi.project.newhope.data.mapper.NewHopeUnInitMapper;
import com.ruoyi.project.newhope.data.service.INewHopeDataService;
import com.ruoyi.project.newhope.device.domain.NewHopeInfraredDevice;
import com.ruoyi.project.newhope.device.mapper.NewHopeInfraredDeviceMapper;
import com.ruoyi.project.newhope.inspection.domain.NewHopeInspection;
import com.ruoyi.project.newhope.inspection.mapper.NewHopeInspectionMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class NewHopeDataServiceImpl implements INewHopeDataService {

    @Autowired
    private NewHopeCollectDataMapper newHopeCollectDataMapper;
    @Autowired
    private NewHopeUnInitMapper newHopeUnInitMapper;
    @Autowired
    private NewHopeInfraredDeviceMapper newHopeInfraredDeviceMapper;
    @Autowired
    private NewHopeInspectionMapper newHopeInspectionMapper;

    @Override
    public List<NewHopeData> selectNewHopeDataList(NewHopeData newHopeData) {
        return newHopeCollectDataMapper.selectNewHopeDataList(newHopeData);
    }

    @Override
    public List<EchartsVO> echartsData(NewHopeData newHopeData) {
        List<NewHopeData> list = new ArrayList<>();
        // 查询正在运行的近红外设备
        List<NewHopeInfraredDevice> deviceIds = newHopeInfraredDeviceMapper.selectDeviceIds();
        for (NewHopeInfraredDevice device : deviceIds) {
            if (Objects.isNull(device.getMaterialCode())) {
                continue;
            }

            // 根据materialCode查询当前物料关联的采集指标
            List<NewHopeInspection> inspections = newHopeInspectionMapper.queryInspectionByMaterialCode(device.getMaterialCode());
            if (CollUtil.isNotEmpty(inspections)) {
                List<NewHopeData> hopeData = newHopeCollectDataMapper.selectNewHopeDataListByDeviceId(device.getId().intValue(), inspections.size() * 20);
                if (hopeData.size() > 0) {
                    list.addAll(hopeData);
                }
            }
        }

        List<EchartsVO> result = new ArrayList<>();
        //查询出未初始化的物料
        List<NewHopeUnInit> unList = newHopeUnInitMapper.selectList();
        for (NewHopeUnInit newHopeUnInit : unList) {
            EchartsVO echartsVO = new EchartsVO();
            echartsVO.setMaterialName(newHopeUnInit.getErrMessage());
            echartsVO.setLocation(newHopeUnInit.getLocation());
            echartsVO.setData(new ArrayList<>());
            echartsVO.setDeviceId(newHopeUnInit.getDeviceId());
            result.add(echartsVO);
        }
        List<String> collect = unList.stream().map(NewHopeUnInit::getLocation).collect(Collectors.toList());

        //采集数据根据检测点进行分组
        Map<String, List<NewHopeData>> dataMap = list.stream().collect(Collectors.groupingBy(item -> item.getDeviceId() + "-" + item.getMaterialName()));
        dataMap.forEach((key, newDataList) -> {
            String location = (newDataList != null && newDataList.size()>0) ? newDataList.get(0).getDeviceLocation() : "未知";
            //当前检测点是否已经存在于未初始化物料的检测点中
            if (collect.contains(location)) {
                return;
            }

            //组装采集前端展示数据
            EchartsVO echartsVO = new EchartsVO();
            echartsVO.setMaterialName(key.split("-")[1]);
            echartsVO.setLocation(location);
            echartsVO.setData(new ArrayList<>());
            if (CollectionUtils.isNotEmpty(newDataList)) {
                echartsVO.setData(newDataList);
                echartsVO.setDeviceId(newDataList.get(0).getDeviceId());
            }

            //处理：如果采集数据中的最新一条距离现在的时间相差超过10分钟，则返回：当前没有检测到有物料流动
            if (CollUtil.isNotEmpty(echartsVO.getData()) && echartsVO.getData().size()>=1) {
                NewHopeData firstData = echartsVO.getData().get(0);
                if (firstData != null && Objects.nonNull(firstData.getCreateTime())) {
                    long minNum = DateUtil.between(firstData.getCreateTime(), new Date(), DateUnit.MINUTE, true);
                    if (minNum > 10) {
                        log.info("采集数据中的最新一条距离现在的时间相差超过10分钟，返回：当前没有检测到有物料流动");
                        echartsVO.setMaterialName("当前没有检测到有物料流动");
                        echartsVO.setData(new ArrayList<>());
                    }
                }
            }
            result.add(echartsVO);
        });

        List<EchartsVO> results = result.stream().sorted(Comparator.comparing(EchartsVO::getDeviceId)).collect(Collectors.toList());
        return results;
    }

//    @Override
//    public List<EchartsVO> echartsData(NewHopeData newHopeData) {
//        List<NewHopeData> list = new ArrayList<>();
//        // 查询采集的分组
//        List<Integer> deviceIds = newHopeCollectDataMapper.selectDataDeviceIds();
//        deviceIds = deviceIds.stream().sorted().collect(Collectors.toList());
//        for (Integer deviceId : deviceIds) {
//            int count = newHopeCollectDataMapper.countDeviceInspections(deviceId);
//            if (count > 0) {
//                List<NewHopeData> hopeData = newHopeCollectDataMapper.selectNewHopeDataListByDeviceId(deviceId, count * 20);
//                if (hopeData.size() > 0) {
//                    list.addAll(hopeData);
//                }
//            }
//        }
//
//        List<EchartsVO> result = new ArrayList<>();
//        //查询出未初始化的物料
//        List<NewHopeUnInit> unList = newHopeUnInitMapper.selectList();
//        for (NewHopeUnInit newHopeUnInit : unList) {
//            EchartsVO echartsVO = new EchartsVO();
//            echartsVO.setMaterialName(newHopeUnInit.getErrMessage());
//            echartsVO.setLocation(newHopeUnInit.getLocation());
//            echartsVO.setData(new ArrayList<>());
//            echartsVO.setDeviceId(newHopeUnInit.getDeviceId());
//            result.add(echartsVO);
//        }
//        List<String> collect = unList.stream().map(NewHopeUnInit::getLocation).collect(Collectors.toList());
//
//        //采集数据根据检测点进行分组
//        Map<String, List<NewHopeData>> dataMap = list.stream().collect(Collectors.groupingBy(NewHopeData::getMaterialName));
//        dataMap.forEach((key, newDataList) -> {
//            String location = (newDataList != null && newDataList.size()>0) ? newDataList.get(0).getDeviceLocation() : "未知";
//            //当前检测点是否已经存在于未初始化物料的检测点中
//            if (collect.contains(location)) {
//                return;
//            }
//
//            //组装采集前端展示数据
//            EchartsVO echartsVO = new EchartsVO();
//            echartsVO.setMaterialName(key);
//            echartsVO.setLocation(location);
//            echartsVO.setData(new ArrayList<>());
//            if (CollectionUtils.isNotEmpty(newDataList)) {
//                echartsVO.setData(newDataList);
//                echartsVO.setDeviceId(newDataList.get(0).getDeviceId());
//            }
//
//            //处理：如果采集数据中的最新一条距离现在的时间相差超过10分钟，则返回：当前没有检测到有物料流动
////            if (CollUtil.isNotEmpty(echartsVO.getData()) && echartsVO.getData().size()>=1) {
////                NewHopeData firstData = echartsVO.getData().get(0);
////                if (firstData != null && Objects.nonNull(firstData.getCreateTime())) {
////                    long minNum = DateUtil.between(firstData.getCreateTime(), new Date(), DateUnit.MINUTE, true);
////                    if (minNum > 10) {
////                        log.info("采集数据中的最新一条距离现在的时间相差超过10分钟，返回：当前没有检测到有物料流动");
////                        echartsVO.setMaterialName("当前没有检测到有物料流动");
////                        echartsVO.setData(new ArrayList<>());
////                    }
////                }
////            }
//            result.add(echartsVO);
//        });
//
//        List<EchartsVO> results = result.stream().sorted(Comparator.comparing(EchartsVO::getDeviceId)).collect(Collectors.toList());
//        return results;
//    }

}
